//
//  HomeViewController.swift
//  WeiBoOfSwift
//
//  Created by aven wu on 20/04/2018.
//  Copyright © 2018 GML. All rights reserved.
//

import UIKit

class HomeViewController: VistorBaseViewController{
    let homeCellID = "homeCellID"
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(popoverAnimatorWillShow), name: NSNotification.Name(rawValue: GMLPopoverAnimatorWillShow), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(popoverAnimatorWillDissmiss), name: NSNotification.Name(rawValue: GMLPopoverAnimatorWillDissmiss), object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
   
    @objc func popoverAnimatorWillShow() -> Void {
        let titleButton = navigationItem.titleView as! NaviTitleButton
        titleButton.isSelected = !titleButton.isSelected
    }
    @objc func popoverAnimatorWillDissmiss() -> Void {
        let titleButton = navigationItem.titleView as! NaviTitleButton
        titleButton.isSelected = !titleButton.isSelected
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNav()
        view.addSubview(tabView)
        tabView.addSubview(refreshControl)
        
        // 如果没有登录  设置未登录界面
        if userlogin == false {
            vistorView?.setUpVisitorInfo(isHome: true, imageName: "visitordiscover_feed_image_smallicon", message: "关注他人，时刻获取他人最新动态")
//            return
        }else{
          
            loadData()
//            Status.loadStatuses(since_id: <#T##Int#>, finished: { (models, error) in
//
//            })
        }
    }

   private func setUpNav(){
    navigationItem.leftBarButtonItem  = UIBarButtonItem.creatCustomBarButtonItem(imageName: "navigationbar_friendattention", highlightedName: "navigationbar_friendattention_highlighted",title:"", target: self, action: #selector(leftBarButtonItemClick))
    
        navigationItem.rightBarButtonItem  = UIBarButtonItem.creatCustomBarButtonItem(imageName: "navigationbar_pop", highlightedName: "navigationbar_pop_highlighted",title:"", target: self, action: #selector(rightBarButtonItemClick))
        let titleButton = NaviTitleButton()
        titleButton.setTitle("欢迎  ", for: UIControlState.normal)
        titleButton.addTarget(self, action: #selector(HomeViewController.titleButtonClick(titleButton:)), for: UIControlEvents.touchUpInside)
        navigationItem.titleView = titleButton
    }
    @objc private func titleButtonClick(titleButton:NaviTitleButton){
        print("带参")
        let nextPopVC = PopoverViewController()
        nextPopVC.transitioningDelegate = popAnimator
        nextPopVC.modalPresentationStyle = UIModalPresentationStyle.custom
        present(nextPopVC, animated: true, completion: {
            
        })
    }
    
    
    @objc private func leftBarButtonItemClick(){
        
    }
    @objc private func rightBarButtonItemClick(){
       
        
    }
    override func loginBtnClick() {
        super.loginBtnClick()
        let navi = UINavigationController()
        navi.addChildViewController(OAuhtViewController())
        present(navi, animated: true) {
            
        }
        
    }

    private lazy var popAnimator:PopoverAnimator = {
        let pop = PopoverAnimator()
        
        return pop
    }()
    
    private lazy var tabView:UITableView = {
        let tab = UITableView(frame:CGRect(x:self.view.frame.origin.x, y: self.view.frame.origin.y+SAFE_SCREEN_TOP, width: self.view.bounds.width, height: self.view.bounds.height-SAFE_SCREEN_BOTTOM-SAFE_SCREEN_TOP-44), style: UITableViewStyle.plain)
        tab.separatorStyle = UITableViewCellSeparatorStyle.none
        tab.register(StatusForwardTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.NormalCell.rawValue)
        tab.register(StatusForwardTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.ForwardCell.rawValue)
        tab.backgroundColor = UIColor.randomColor
        if #available(iOS 11.0, *){
            tab.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.never
        }
        tab.delegate = self
        tab.dataSource = self
        return tab
    }()
    
    private lazy var  refreshControl :HomeRefreshControl = {
        let refreshControl = HomeRefreshControl()
        refreshControl.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
        return refreshControl
    }()
    
    
    /**
     获取微博数据
     如果想调用一个私有的方法:
     1.去掉private
     2.@objc, 当做OC方法来处理
     */
    @objc private func loadData()
    {
        let since_id = dataList?.first?.id ?? 0
        
        Status.loadStatuses(since_id: since_id) { (models, error) -> () in
            
            // 接收刷新
            self.refreshControl.endRefreshing()
            
            if error != nil
            {
                return
            }
            // 下拉刷新
            if since_id > 0
            {
                // 如果是下拉刷新, 就将获取到的数据, 拼接在原有数据的前面
                self.dataList = models! + self.dataList!
            }else
            {
                self.dataList = models
            }
        }
        
    }
    
    // 保存请求的数组
    var dataList:[Status]?
    {
        didSet {
            tabView.reloadData()
        }
    }
    
    /// 微博行高的缓存, 利用字典作为容器. key就是微博的id, 值就是对应微博的行高
    var rowCache: [Int: CGFloat] = [Int: CGFloat]()
    
    override func didReceiveMemoryWarning() {
        // 清空缓存
        rowCache.removeAll()
    }

    
}

//MARK: UITableViewDelegate
extension HomeViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let status = dataList![indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: StatusTableViewCellIdentifier.cellID(status: status)) as! StatusTableViewCell
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.status = status
        cell.cellDelegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       
        // 1.取出对应行的模型
        let status = dataList![indexPath.row]
        
        // 2.判断缓存中有没有
        if let height = rowCache[status.id]
        {
            print("从缓存中获取====\(height)  index =\(indexPath.row)  id = \(status.id)")
            return height
        }
        
        // 3.拿到cell
        let cell = tableView.dequeueReusableCell(withIdentifier: StatusTableViewCellIdentifier.cellID(status: status)) as! StatusTableViewCell

        // 4.拿到对应行的行高
        let rowHeight = cell.rowHeight(status: status)
        
        // 5.缓存行高
        rowCache[status.id] = rowHeight
        print("重新计算")
        
        // 6.返回行高
        return rowHeight
    }
}

extension HomeViewController:StatusTableViewCellDelegate {
    
    func statusTableViewCell(cell: StatusTableViewCell, index: Int, picUrl: [NSURL]) {
        
        // 1.创建图片浏览器
        let vc = PhotoBrowserController(index: index, urls: picUrl)
        
        // 2.显示图片浏览器
        present(vc, animated: true, completion: nil)
        
    }
}
